<template>
  <div class="modal-overlay" v-if="visible">
    <div class="modal-container">
      <div class="modal-header">
        <h3>{{ title }}</h3>
        <button class="close-btn" @click="$emit('close')">&times;</button>
      </div>
      <form @submit.prevent="$emit('confirm', formData)">
        <div class="form-group">
          <label>名称</label>
          <input v-model="formData.name" required>
        </div>

        <template v-if="type === 'dish'">
          <div class="form-group">
            <label>价格</label>
            <input
                v-model="formData.price"
                type="number"
                step="0.01"
                min="0"
                required
            >
          </div>
        </template>

        <template v-if="type === 'restaurant'">
          <div class="form-group">
            <label>地址</label>
            <input v-model="formData.address" required>
          </div>
        </template>

        <div class="form-actions">
          <button type="button" class="secondary-btn" @click="$emit('close')">
            取消
          </button>
          <button type="submit" class="primary-btn">
            {{ isEdit ? '保存' : '创建' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'

const props = defineProps({
  visible: Boolean,
  type: String,
  data: Object
})

const emit = defineEmits(['close', 'confirm'])

const formData = ref({
  name: '',
  price: '',
  address: ''
})

const isEdit = computed(() => !!props.data?.id)
const title = computed(() => {
  const types = {
    restaurant: '餐厅',
    department: '部门',
    dish: '菜品'
  }
  return `${isEdit.value ? '编辑' : '新建'}${types[props.type]}`
})

watch(() => props.data, (newVal) => {
  formData.value = {
    name: newVal?.name || '',
    price: newVal?.price || '',
    address: newVal?.address || ''
  }
}, { immediate: true })
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-container {
  background: white;
  border-radius: 8px;
  padding: 2rem;
  width: 90%;
  max-width: 500px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #64748b;
}

.form-group {
  margin-bottom: 1.2rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #475569;
}

.form-group input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  font-size: 1rem;
}

.form-actions {
  margin-top: 2rem;
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
}
</style>